document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('addPositionForm');

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        clearErrors();

        if (validateForm()) {
            form.submit();
        }
    });

    function validateForm() {
        let isValid = true;

        // 验证职位名称
        const nameInput = document.getElementById('positionName');
        if (!nameInput.value.trim()) {
            showError('positionName', '请输入职位名称');
            isValid = false;
        } else if (nameInput.value.trim().length > 50) {
            showError('positionName', '职位名称不能超过50个字符');
            isValid = false;
        }

        // 验证职位代码
        const codeInput = document.getElementById('positionCode');
        if (!codeInput.value.trim()) {
            showError('positionCode', '请输入职位代码');
            isValid = false;
        } else if (!/^[a-zA-Z0-9_-]+$/.test(codeInput.value.trim())) {
            showError('positionCode', '职位代码只能包含字母、数字、下划线和横线');
            isValid = false;
        } else if (codeInput.value.trim().length > 20) {
            showError('positionCode', '职位代码不能超过20个字符');
            isValid = false;
        }

        // 验证部门
        const deptSelect = document.getElementById('departmentId');
        if (!deptSelect.value) {
            showError('departmentId', '请选择所属部门');
            isValid = false;
        }

        // 验证角色
        const roleSelect = document.getElementById('positionRoleId');
        if (!roleSelect.value) {
            showError('positionRoleId', '请选择职位角色');
            isValid = false;
        }

        return isValid;
    }

    function showError(fieldId, message) {
        const errorElement = document.querySelector(`[id$=${fieldId}-error]`);
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }
    }

    function clearErrors() {
        const errorElements = document.querySelectorAll('.error-message');
        errorElements.forEach(element => {
            element.textContent = '';
            element.style.display = 'none';
        });
    }
});